import { Sequelize, Op } from 'sequelize'
import env from './index.ts'
let seq: any = null
;(async () => {
  const { MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB } = env
  // console.log(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB)

  seq = new Sequelize(MYSQL_DB!, MYSQL_USER!, MYSQL_PASSWORD, {
    host: MYSQL_HOST,
    port: Number(MYSQL_PORT),
    dialect: 'mysql',
    timezone: '+08:00',
    operatorsAliases: {
      $like: Op.like,
      $substring: Op.substring,
      $lt: Op.lt,
      $gt: Op.gt,
      $and: Op.and,
      $or: Op.or,
    },
    pool: {
      max: 200,
      min: 0,
      idle: 100 * 1000, // 空闲时间
      acquire: 100 * 1000, // 超时时间
    },
    dialectOptions: {
      typeCast: true,
      dateStrings: true, // typeCast,dateStrings 格式化日期
    },
    define: {
      timestamps: true,
      createdAt: 'created_time',
      updatedAt: 'updated_time',
    },
  })

  await seq
    .authenticate()
    .then(() => {
      console.log('数据库连接成功')
    })
    .catch(() => {
      console.log('数据库连接失败')
    })

  // 使表模型和数据库表模型匹配
  // await seq.sync({ alter: true })

  // 将创建表,如果表已经存在,则将其首先删除
  // await seq.sync({ force: true })
})()

export default seq
